﻿package ascript.components.ai
{
	//#########################
	// Header Includes
	//#########################
	import ascript.Game;
	import Box2D.Common.Math.b2Vec2;
	import ascript.GameComponent;
	import ascript.GameLevel;
	import ascript.GameObject;
	import ascript.utilities.PointSimple;
	
	//#########################
	// AIPatrol Class
	//#########################
	public class AIWaypoint extends GameComponent
	{
		//=========================
		// Constructors
		//=========================	
		public function AIWaypoint():void
		{
		}
		
		//=========================
		// Members
		//=========================	
		override public function initComponent( tGame:Game, tObject:GameObject ):void
		{
			// Set Default Attributes
			defaultAttribute( tObject, "WaypointIsActive", true );
			defaultAttribute( tObject, "Waypoints", new Vector.<b2Vec2> );
			defaultAttribute( tObject, "WaypointCurrent", 0 );
			defaultAttribute( tObject, "WaypointIsLooping", true );
			defaultAttribute( tObject, "WaypointUpdateDelay", 10 );
			defaultAttribute( tObject, "WaypointTimer", 0 );
		}
				
		override public function updateComponent( tGame:Game, tObject:GameObject, tLevel:GameLevel ):void
		{		
			if ( tObject.getAttribute( "WaypointIsActive" ) )
			{
				if ( ( tGame.time - tObject.getAttribute( "WaypointTimer" ) ) >= tObject.getAttribute( "WaypointUpdateDelay" ) )
				{
					var tempDirection:b2Vec2 = ( tObject.getAttribute( "Waypoints" )[ tObject.getAttribute( "WaypointCurrent" ) ] ).Copy();
					tempDirection.Subtract( tObject.getAttribute( "Location" ) );
										
					tObject.setAttribute( "WaypointTimer", tGame.time );
					
					if ( tempDirection.Length() < 100 )
					{
						var tempCurrent:int = tObject.getAttribute( "WaypointCurrent" ) + 1;
						if ( tempCurrent >= ( tObject.getAttribute( "Waypoints" ) ).length )
						{
							tempCurrent = 0;
							
							if ( !tObject.getAttribute( "WaypointIsLooping" ) )
							{
								tObject.setAttribute( "Direction", new b2Vec2() );
								tObject.setAttribute( "WaypointIsActive", false );
							}
						}
						tObject.setAttribute( "WaypointCurrent", tempCurrent );
					}
					else
					{
						tempDirection.Normalize();
						tObject.setAttribute( "Direction", tempDirection );
					}
				}
			}
		}
	}
}